//
// Created by martin on 2/6/22.
//

#ifndef MUDUO_LOGFILE_H
#define MUDUO_LOGFILE_H

#include "muduo/base/Types.h"
#include "muduo/base/Mutex.h"
#include "muduo/base/noncopyable.h"

#include <memory>

namespace muduo
{

namespace FileUtil
{
class AppendFile;
} // namespace FileUtil

/**
 * Write log message to file
 */
class LogFile : noncopyable
{
public:
    LogFile(const string& basename,
            off_t rollSize,
            bool threadSafe = true,
            int flushInterval = 3,
            int checkEveryN = 1024);
    ~LogFile();

    bool rollFile();

    // may be call by multi-thread, if so, think about thread-safe

    void append(const char* logline, int len);
    void flush();

private:
    void append_unlocked(const char* logline, int len);
    static string getLogFileName(const string& basename, time_t* now);

    const string basename_;
    // roll size threshold: when log file fileSize > rollSize_, need roll file
    const off_t rollSize_;
    // flush time threshold: when now time > flushInterval_, need fflush content to file
    const int flushInterval_;
    const int checkEveryN_;

    int count_;

    std::unique_ptr<MutexLock> mutex_; // NULL: thread-unsafe; non-NULL: thread-safe
    time_t startOfPeriod_; // roll time / kRollPerSeconds_ * kRollPerSeconds_
    time_t lastRoll_;      // last roll time
    time_t lastFlush_;     // last fflush time
    std::unique_ptr<FileUtil::AppendFile> file_;

    // 1day = 60 * 60 * 24 seconds
    static const int kRollPerSeconds_ = 60 * 60 * 24;
};

} // namespace muduo

#endif //MUDUO_LOGFILE_H
